package yelmor.comm100.api;

import com.fasterxml.jackson.annotation.JsonCreator;
import org.igniterealtime.restclient.entity.UserEntities;
import org.igniterealtime.restclient.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.json.JsonParser;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import yelmor.comm100.bean.OpenfireApi;
import yelmor.comm100.domain.CoUser;
import yelmor.comm100.repository.CoUserRepository;
import yelmor.comm100.repository.CoUserRoleRepository;
import yelmor.comm100.util.SecurityUtil;

import java.util.List;

/**
 * Created by yel on 4/28/16.
 */
@RestController
public class CoUserManipulate {

  @Autowired
  private OpenfireApi openfireApi;

  @Autowired
  private CoUserRepository coUserRepository;

  @Autowired
  private CoUserRoleRepository coUserRoleRepository;

  @RequestMapping(path = "/api/gets", method = RequestMethod.GET)
  public List<UserEntity> getServicesGet() {
    String userName = SecurityUtil.getCurrentUserName();
    CoUser coUser = coUserRepository.findOne(userName);
    UserEntities userEntits = openfireApi.getServiceUser(coUser.getSiteCode());
    JacksonJsonParser jacksonJsonParser = new JacksonJsonParser();
    List<UserEntity> userEntityList = userEntits.getUsers();
    return userEntityList;
  }

  @RequestMapping(path = "/api/addService", method = RequestMethod.GET)
  public void addServiceGet(@RequestParam(value="serviceName") String serviceName
                          , @RequestParam(value="servicePasswd") String servicePasswd) {
    CoUser curUser = coUserRepository.findOne(SecurityUtil.getCurrentUserName());
    System.out.println("request add service with " + serviceName + ", " + servicePasswd);
    String serviceFullName = serviceName + "-service-" + curUser.getSiteCode();
    openfireApi.createOfUser(serviceFullName, serviceName, servicePasswd);
    openfireApi.addUserToGroup(serviceFullName, curUser.getSiteCode());
    return;
  }

  @RequestMapping(path = "/api/deleteService", method = RequestMethod.GET)
  public void deleteServiceGet(@RequestParam(value="serviceName") String serviceName) {
    openfireApi.getRestApiClient().deleteUser(serviceName);
    return;
  }
}
